import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:opencv_dart/opencv_dart.dart' as cv;
import 'package:flutter/material.dart';

class PickImage extends StatefulWidget {
  const PickImage({super.key, this.detector});
  final cv.FaceDetectorYN? detector;

  @override
  State<PickImage> createState() => _PickImageState();
}

/// 图片识别
class _PickImageState extends State<PickImage> {
  Uint8List? imgData;
  String text = "";
  cv.Mat? mat;
  cv.FaceDetectorYN? detector;

  @override
  void initState() {
    super.initState();
  }

  void detect() {
    const size = (320, 320);
    detector!.setInputSize(size);
    final dst = cv.Mat.create();
    cv.resize(
      mat!,
      size,
      dst: dst,
      interpolation: cv.INTER_AREA,
      fx: 0,
      fy: 0,
    );
    final faces = detector!.detect(dst);

    text = faces.rows.toString();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: ListView(
        children: [
          ElevatedButton(
            onPressed: () async {
              final picker = ImagePicker();
              final img = await picker.pickImage(source: ImageSource.gallery);
              if (img != null) {
                final path = img.path;
                mat = cv.imread(path);
                if (mat == null) return;
                // heavy computation
                imgData = cv.imencode(".png", mat!).$2;
                detect();
              }
            },
            child: const Text("Pick Image"),
          ),
          ElevatedButton(
            onPressed: () async {
              final picker = ImagePicker();
              final img = await picker.pickImage(source: ImageSource.camera);
              if (img != null) {
                final path = img.path;
                mat = cv.imread(path);
                if (mat == null) return;
                // heavy computation
                imgData = cv.imencode(".png", mat!).$2;
                detect();
              }
            },
            child: const Text("take Image"),
          ),
          if (imgData != null) ...[
            Text(text),
            Image.memory(imgData!),
          ],
        ],
      ),
    );
  }
}
